package com.yuyang.wifi.jobservice;

import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.yuyang.wifi.R;
import com.yuyang.wifi.activitys.mine.LockScreenActivity;
import com.yuyang.wifi.base.AppManager;
import com.yuyang.wifi.constant.AppConstant;
import com.yuyang.wifi.receiver.AppReceiver;
import com.yuyang.wifi.utils.ActivityAllManager;
import com.yuyang.wifi.utils.Parser;
import com.yuyang.wifi.utils.PreferencesProviderUtils;

import java.util.Calendar;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.annotation.PluralsRes;
import androidx.core.app.AlarmManagerCompat;
import androidx.core.app.NotificationCompat;
import cn.jpush.android.service.AlarmReceiver;


public class AppService extends Service {

    private AppReceiver mLockScreenReceiver;
    private IntentFilter mIntentFilter = new IntentFilter();
    private IntentFilter mIntentFilterPackage = new IntentFilter();
    private Context mContext;
    private Handler handler = new Handler();
    private static AlarmManager alarmManager;
    private static PendingIntent pendingIntent;
    private static AppService instance;
    private PowerManager.WakeLock wakeLock = null;
    private RemoteViews remoteViews;

    /**
     * 单一实例
     */

//    public static AppService getInstance() {
//        if (instance == null) {
//            instance = new AppService();
//        }
//        return instance;
//    }
    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("TAG", "MyApplication==手机休眠调起");
//        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
//        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, AppService.class.getName());
//        wakeLock.acquire();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.e("TAG", "MyApplication===appservice广播创建了");

        // 监听屏幕关闭和打开的广播必须动态注册
        mIntentFilter.addAction(Intent.ACTION_BOOT_COMPLETED);
        mIntentFilter.addAction(Intent.ACTION_SCREEN_OFF);
        mIntentFilter.addAction(Intent.ACTION_SCREEN_ON);
        mIntentFilter.addAction(Intent.ACTION_TIME_TICK);
        mIntentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
        mIntentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        mIntentFilter.addAction(Intent.ACTION_USER_PRESENT);
        mIntentFilter.addAction("android.net.wifi.supplicant.CONNECTION_CHANGE");
        mIntentFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);

        //package广播
        mIntentFilterPackage.addAction(Intent.ACTION_PACKAGE_ADDED);
        mIntentFilterPackage.addAction(Intent.ACTION_PACKAGE_REMOVED);
        mIntentFilterPackage.addDataScheme("package");

        // 设置广播的优先级为最大
        mIntentFilter.setPriority(Integer.MAX_VALUE);
        mIntentFilterPackage.setPriority(Integer.MAX_VALUE);

        if (null == mLockScreenReceiver) {
            mLockScreenReceiver = new AppReceiver();
            mLockScreenReceiver.setType(1);
            mIntentFilter.setPriority(Integer.MAX_VALUE);
            mIntentFilterPackage.setPriority(Integer.MAX_VALUE);
            registerReceiver(mLockScreenReceiver, mIntentFilter);
            registerReceiver(mLockScreenReceiver, mIntentFilterPackage);
            // Toast.makeText(getApplicationContext(), "AppService", Toast.LENGTH_LONG).show();
        }

        String ID = "com.yuyang.wifi";    //这里的id里面输入自己的项目的包的路径
        String NAME = "Channel One";
        NotificationCompat.Builder builder;
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(ID, NAME, manager.IMPORTANCE_HIGH);
            channel.enableLights(true);
            channel.setShowBadge(true);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            manager.createNotificationChannel(channel);
            builder = new NotificationCompat.Builder(AppService.this).setChannelId(ID);
            remoteViews = new RemoteViews(getPackageName(), R.layout.notification_custom_layout);
            builder.setCustomContentView(remoteViews);
//            NotificationCompatColor.AutomationUse(this)
//                    .setContentTitleColor(remoteViews, R.id.notification_content_title)
//                    .setContentTextColor(remoteViews, R.id.notification_content_text);
//            remoteViews.setTextViewText(R.id.notification_content_title, "Custom ContentTitle 1");
//            remoteViews.setTextViewText(R.id.notification_content_text, "Custom ContentText 2");
//            remoteViews.setImageViewResource(R.id.notification_large_icon, mLargeIconId);
        } else {
            builder = new NotificationCompat.Builder(this);
        }
        builder.setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE);
        builder.setTicker(" ");
        builder.setAutoCancel(false);
        builder.setCustomContentView(remoteViews);
        //builder.setSound(null);
        builder.setNotificationSilent();
        builder.setPriority(NotificationCompat.PRIORITY_MIN);
//        builder.setContentTitle("手机管家持续保护");
//        builder.setContentText(" ");
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_hide));
        builder.setSmallIcon(R.mipmap.ic_launcher_hide);
//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
//            builder.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, LockScreenActivity.class), PendingIntent.FLAG_UPDATE_CURRENT));
//        }
        Notification n = builder.build();
        // 通知栏显示系统图标
        startForeground(0x111, n);
        //stopForeground(true);
        //Parser.killBackgroundProcess(this);

        //return START_STICKY;
        return START_STICKY_COMPATIBILITY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(new Intent(this, AppService.class));
        } else {
            startService(new Intent(this, AppService.class));
        }
        if (mLockScreenReceiver != null) {
            unregisterReceiver(mLockScreenReceiver);
            mLockScreenReceiver = null;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void lunchAC(Context context, int time, String outAdType, String boardType) {
        if (null != alarmManager) {
            Log.e("TAG", "MyApplication===" + "alarmManager.cancel(pendingIntent)");
            alarmManager.cancel(pendingIntent);
        }
        handler.removeCallbacksAndMessages(null);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(outAdType) && "5".equals(outAdType)) {
                    String homeCheck = PreferencesProviderUtils.getString(context, "home_check", AppConstant.KEY_HOME_CHECK, "");
                    Log.e("TAG", "服务===5555" + "" + homeCheck);
                    if (!TextUtils.isEmpty(homeCheck) && "continue".equals(homeCheck)) {
                        String ischangeIcon = PreferencesProviderUtils.getString(context, "change_icon", AppConstant.KEY_CHANGE_ICON, "");
                        String isPlay = PreferencesProviderUtils.getString(context, "hhhh", AppConstant.KEY_IS_PLAYING_AD, "");
                        if (!TextUtils.isEmpty(ischangeIcon) && "change_icon".equals(ischangeIcon)) {
                            //Toast.makeText(context, "我是图标隐藏状态", Toast.LENGTH_LONG).show();
                            Log.e("TAG", "appService==" + "广播触发类型==" + outAdType);
                            Intent intentMainActivity = new Intent(context, LockScreenActivity.class);
                            intentMainActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intentMainActivity.putExtra("mServiceType", "1");
                            intentMainActivity.putExtra("mLockType", outAdType);
                            intentMainActivity.putExtra("board_type", boardType);
                            startActivityByAlarm(context, intentMainActivity);
                        } else {
                            //Toast.makeText(context, "我是第二个判断11==" + isPlay, Toast.LENGTH_LONG).show();
                            ActivityAllManager.getInstance().finishAllActivity();
                            Log.e("TAG", "MyApplication===" + isPlay);
                            Log.e("TAG", "下个任务=== " + isPlay);
                            if (TextUtils.isEmpty(isPlay)) {
                                //Toast.makeText(context, "我是第二个判断22==play", Toast.LENGTH_LONG).show();
                                Log.e("TAG", "appService==" + "广播触发类型==" + outAdType);
                                Intent intentMainActivity = new Intent(context, LockScreenActivity.class);
                                intentMainActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                intentMainActivity.putExtra("mServiceType", "1");
                                intentMainActivity.putExtra("mLockType", outAdType);
                                intentMainActivity.putExtra("board_type", boardType);
                                startActivityByAlarm(context, intentMainActivity);
                            }
                        }
                    }
                } else {
                    String ischangeIcon = PreferencesProviderUtils.getString(context, "change_icon", AppConstant.KEY_CHANGE_ICON, "");
                    String isPlay = PreferencesProviderUtils.getString(context, "hhhh", AppConstant.KEY_IS_PLAYING_AD, "");
                    if (!TextUtils.isEmpty(ischangeIcon) && "change_icon".equals(ischangeIcon)) {
                        //Toast.makeText(context, "我是图标隐藏状态", Toast.LENGTH_LONG).show();
                        Log.e("TAG", "appService==" + "广播触发类型==" + outAdType);
                        Intent intentMainActivity = new Intent(context, LockScreenActivity.class);
                        intentMainActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intentMainActivity.putExtra("mServiceType", "1");
                        intentMainActivity.putExtra("mLockType", outAdType);
                        intentMainActivity.putExtra("board_type", boardType);
                        startActivityByAlarm(context, intentMainActivity);
                    } else {
                        //Toast.makeText(context, "我是第二个判断11==" + isPlay, Toast.LENGTH_LONG).show();
                        ActivityAllManager.getInstance().finishAllActivity();
                        Log.e("TAG", "MyApplication===" + isPlay);
                        Log.e("TAG", "下个任务=== " + isPlay);
                        if (TextUtils.isEmpty(isPlay)) {
                            //Toast.makeText(context, "我是第二个判断22==play", Toast.LENGTH_LONG).show();
                            Log.e("TAG", "appService==" + "广播触发类型==" + outAdType);
                            Intent intentMainActivity = new Intent(context, LockScreenActivity.class);
                            intentMainActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intentMainActivity.putExtra("mServiceType", "1");
                            intentMainActivity.putExtra("mLockType", outAdType);
                            intentMainActivity.putExtra("board_type", boardType);
                            startActivityByAlarm(context, intentMainActivity);
                        }
                    }
                }
            }
        }, time * 1000);
    }

    public static void startActivityByAlarm(Context context, Intent intent) {

        pendingIntent = PendingIntent.getActivity(context, 10104, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        long now = Calendar.getInstance().getTimeInMillis();
//        Log.e("TAG", "获取时间===: " + now);
        setAndAllowWhileIdle(alarmManager, AlarmManager.RTC_WAKEUP, pendingIntent);
    }

    public static void setAndAllowWhileIdle(AlarmManager p0, int type, PendingIntent operation) {
        //版本适配 System.currentTimeMillis()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {// 6.0及以上
//            p0.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
//                    SystemClock.elapsedRealtime(), operation);
            // Log.e("TAG", "下个任务=== " + "alarm");
            p0.setAlarmClock(new AlarmManager.AlarmClockInfo(Calendar.getInstance().getTimeInMillis(), null), operation);


        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {// 4.4及以上
            p0.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(),
                    operation);
        } else {
            p0.set(type, SystemClock.elapsedRealtime(), operation);
        }
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                p0.cancel(operation);
//                Log.e("TAG", "我自己消失了===");
//            }
//        }, 10000);
    }

}
